package com.sdsy.quartz;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sdsy.constant.Config;
import com.sdsy.domain.ContractAddress;
import com.sdsy.domain.TransferAccountsRecordDO;
import com.sdsy.service.TransferAccountsRecordService;
import com.sdsy.service.VipWalletAddrService;
import com.sdsy.util.HttpClientUtil;
import com.sdsy.util.SysUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by yxc on 2018/4/11.
 */
@Configuration
@EnableScheduling
@PropertySource("classpath:config/config.properties")
public class ScheduledTasks {
    //    private static final String url = "http://api-ropsten.etherscan.io/api?module=account&action=txlist&address=Address&startblock=0&endblock=99999999&sort=desc&apikey=YourApiKeyToken";
//    private static final String url = "https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2&address=0x4e83362442b8d1bec281594cea3050c8eb01311c&page=1&offset=100&sort=asc&apikey=YourApiKeyToken";
    private static final String url = "http://api.etherscan.io/api?module=account&action=txlist&address=ADDRESS&sort=desc&apikey=APIKEY";
//    private static final String url = "https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=ADDRESS&sort=desc&apikey=APIKEY";


    private static final Logger logger = LoggerFactory.getLogger(ScheduledTasks.class);
    /**测试**/
    //  private static final String WEB3J = "https://ropsten.infura.io/c8LMJFLLL7rUEBtxozvJ";
    /**
     * 正式
     **/
    private static final String WEB3J = "https://mainnet.infura.io/c8LMJFLLL7rUEBtxozvJ";
    private static final int min_thred_num = 1;
    private static final int max_thred_num = 5;

//    @Value("${wallet.account}")
//    private String toAddress;

    @Value("${wallet.smart_contract_address}")
    private String hyAddress;

    @Value("${wallet.apikey}")
    private String apikey;


    @Autowired
    private Config config;
    @Autowired
    private TransferAccountsRecordService transferAccountsRecordService;

    @Autowired
    private VipWalletAddrService vipWalletAddrService;

    @Scheduled(cron = "${quratz_expression}") // 每10分钟执行一次
    public void save() {
        insertWalletByLog();
    }


    /**
     * 失败后日志记录
     */
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public void insert(TransferAccountsRecordDO transferAccountsRecordDO) {
        transferAccountsRecordService.insert(transferAccountsRecordDO);
    }


    public static void main(String[] args) {
//        Date date = new Date(Long.parseLong("1523549938") * 1000L);
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        System.out.println(simpleDateFormat.format(date));
        String str = "0xa9059cbb000000000000000000000000a415aa98334d61e2d06c5d92a5f9079a420fe2860000000000000000000000000000000000000000000000008ac7230489e80000";
        String info = str.substring(74, str.length());
        System.out.println(info.length());
    }

    /**
     * 根据日志获取交易记录
     */
    public void insertWalletByLog() {

        List<String> walletrecordlist = queryWalletRecordList();
        String path = url.replace("ADDRESS", hyAddress).replace("APIKEY", apikey);
        String info = HttpClientUtil.doGet(path);
        JSONObject jsonObject = JSONUtil.parseObj(info);
        String result = jsonObject.getStr("result");
        JSONArray jsonArray = JSONUtil.parseArray(result);
        List<ContractAddress> list = jsonArray.toList(ContractAddress.class);
        if (!SysUtil.isNull(list) && list.size() > 0) {
            int len = list.size();
            int threadNum = getThredNum(list.size());
            CountDownLatch countDownLatch = new CountDownLatch(threadNum);
            // 创建线程池
            ExecutorService threadPool = Executors.newFixedThreadPool(threadNum);
            int record = len % threadNum > 0 ? len / threadNum + 1 : len / threadNum;
            for (int i = 1; i <= threadNum; i++) {
                int beginIndex = i == 1 ? 0 : record * (i - 1);
                int endIndex = i == threadNum ? len : record * i;
                List<ContractAddress> logResultList = list.subList(beginIndex, endIndex);
                threadPool.execute(new WalletRecordThred(logResultList, countDownLatch, transferAccountsRecordService, walletrecordlist, apikey));
            }
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                threadPool.shutdown();
            }
        } else {
            logger.info("insertWalletByLog数据为空!");
        }
    }

    private int getThredNum(int size) {
        int num = size < 50 ? min_thred_num : size / 50 + 1;
        return num > max_thred_num ? max_thred_num : num;
    }

    /**
     * 查询记录
     */
    public List<String> queryWalletRecordList() {
        return transferAccountsRecordService.queryWalletRecordList();
    }
}
